using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Musicman.Business;
using System.Collections.Generic;
using System.IO;
using Musicman.Common;
using System.Threading;
using Musicman.Entities.BusinessEntities;

namespace Musicman.SAL
{
    /// <summary>
    /// Summary description for FileManagerService
    /// </summary>
    [WebService(Namespace = "http://vpankovic.musicman.com/webservices")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class FileManagerService : System.Web.Services.WebService
    {
        public FileDownloadHeader FileDownload;

        [WebMethod]
        public List<Musicman.Entities.BusinessEntities.SearchResult> GetPendingDownloads(long userID)
        {
            List<Musicman.Entities.BusinessEntities.SearchResult> res = DataManager.Instance.GetPendingDownloads(userID);
            return res;
        }

        [WebMethod]
        public bool AddPendingDownloads(long userID, List<long> filesIDs)
        {
            bool res = DataManager.Instance.AddPendingDownloadsList(userID, filesIDs);
            return res;
        }

        [WebMethod]
        public bool RemovePendingDovnload(long userID, long fileID, int num)
        {
            bool res = DataManager.Instance.RemovePendingDownload(userID, fileID, num);
            return res;
        }

        [WebMethod]
        public bool RemovePendingDovnloadList(long userID, List<long> fileIDs, int num)
        {
            bool res = DataManager.Instance.RemovePendingDownloadList(userID, fileIDs, num);
            return res;
        }

        [WebMethod]
        public List<Musicman.Entities.Searchjob> GetSearchJobs()
        {
            List<Musicman.Entities.Searchjob> res = DataManager.Instance.GetAllSearchJobs();
            return res;
        }

        [WebMethod]
        public List<Musicman.Entities.BusinessEntities.SearchResult> SearchFiles(int top, long jobID, string fileName)
        {
            List<Musicman.Entities.BusinessEntities.SearchResult> res = DataManager.Instance.SearhFiles(top, jobID, fileName);
            return res;
        }

        [WebMethod]
        public List<Musicman.Entities.BusinessEntities.SearchResult> TopDownloads(long jobID, string fileName, int count)
        {
            List<Musicman.Entities.BusinessEntities.SearchResult> res = DataManager.Instance.GetTopDownloads(jobID, fileName, count);
            return res;
        }

        [WebMethod]
        public List<Musicman.Entities.BusinessEntities.SearchResult> TopRated(long jobID, string fileName, int count)
        {
            List<Musicman.Entities.BusinessEntities.SearchResult> res = DataManager.Instance.GetTopRated(jobID, fileName, count);
            return res;
        }

        [WebMethod]
        public List<Musicman.Entities.BusinessEntities.SearchResult> SearchFilesRandom(long jobID, string fileName, int top)
        {
            List<Musicman.Entities.BusinessEntities.SearchResult> res = DataManager.Instance.SearchFilesRandom(jobID, fileName, top);
            return res;
        }

        [WebMethod]
        public List<Musicman.Entities.BusinessEntities.SearchResult> SearchFilesLatest(long jobID, string fileName, int top)
        {
            List<Musicman.Entities.BusinessEntities.SearchResult> res = DataManager.Instance.SearchLatest(jobID, fileName, top);
            return res;
        }

        [WebMethod]
        public Musicman.Entities.SearchFileStat GetFileStats(long fileID)
        {
            Musicman.Entities.SearchFileStat res = DataManager.Instance.GetSearchFileStats(fileID);
            return res;
        }

        [WebMethod]
        public bool UpdateFileStats(long fileID, int mark)
        {
            bool res = DataManager.Instance.UpdateSearchFileStats(fileID, mark);
            return res;
        }

        [WebMethod]
        public bool UpdateDownloadStats(long personID, long fileID, int num)
        {
            bool res = DataManager.Instance.UpdateDownloadStats(personID, fileID, num);
            return res;
        }

        [WebMethod]
        [SoapHeader("FileDownload", Direction = SoapHeaderDirection.InOut)]
        public byte[] DownloadFile(long personID, long fileID)
        {
            Musicman.Entities.BusinessEntities.SearchResult file = DataManager.Instance.GetSearchResult(fileID);
            FileDownload.exists = File.Exists(file.Fullpath);
            byte[] res = new byte[0];
            if (FileDownload.exists)
            {
                FileStream fs = null;
                try
                {
                    fs = File.Open(file.Fullpath, FileMode.Open, FileAccess.Read);
                    res = new byte[fs.Length];
                    fs.Read(res, 0, (int)fs.Length);
                    fs.Close();
                    DataManager.Instance.UpdateDownloadStats(personID, fileID, 1);
                }
                catch (Exception ex)
                {
                    if (fs != null) { fs.Close(); }
                    LogManager.LogException("File open error", ex);
                    FileDownload.exists = false;
                }
            }
            if (res.Length == 0)
            {
                FileDownload.exists = false;
            }
            return res;
        }

        [WebMethod]
        [SoapHeader("FileDownload", Direction = SoapHeaderDirection.InOut)]
        public byte[] DownloadFilePath(long personID, string fullPath)
        {
            FileDownload.exists = File.Exists(fullPath);
            byte[] res = new byte[0];
            if (FileDownload.exists)
            {
                FileStream fs = null;
                try
                {
                    fs = File.Open(fullPath, FileMode.Open, FileAccess.Read);
                    res = new byte[fs.Length];
                    fs.Read(res, 0, (int)fs.Length);
                    fs.Close();
                    DataManager.Instance.UpdateDownloadStats(personID, 0, 1);
                }
                catch (Exception ex)
                {
                    if (fs != null) { fs.Close(); }
                    LogManager.LogException("File open error", ex);
                    FileDownload.exists = false;
                }
            }
            if (res.Length == 0)
            {
                FileDownload.exists = false;
            }
            return res;
        }

        [WebMethod]
        public void LogClientException(long personID, string errorDesc, string exceptionMessage, string innerExceptionMessage)
        {
            Musicman.Entities.User user = DataManager.Instance.GetUserInfo(personID);
            string message = String.Format("Client user : {0}, {1} {2} \r\n {3}", user.Emailaddress, user.Firstname, user.Lastname, errorDesc);
            Exception ex = null;
            if (String.IsNullOrEmpty(innerExceptionMessage))
            {
                ex = new Exception(exceptionMessage);
            }
            else
            {
                ex = new Exception(exceptionMessage, new Exception(innerExceptionMessage));
            }
            LogManager.LogException(message, ex);
        }

        [WebMethod]
        public UserActivity GetUserActivity(long personID)
        {
            UserActivity res = DataManager.Instance.GetUserActivity(personID);
            return res;
        }

        [WebMethod]
        public List<Musicman.Entities.BusinessEntities.UserActivity> GetTopLoggers(int top)
        {
            List<Musicman.Entities.BusinessEntities.UserActivity> res = DataManager.Instance.GetTopLoggers(1, top);
            return res;
        }

        [WebMethod]
        public List<Musicman.Entities.BusinessEntities.UserActivity> GetTopDownloaders(int top)
        {
            List<Musicman.Entities.BusinessEntities.UserActivity> res = DataManager.Instance.GetTopDownloaders(1, top);
            return res;
        }

        [WebMethod]
        public List<Musicman.Entities.BusinessEntities.SearchResult> GetFolderFiles(long searchFileid, string loaction)
        {
            List<Musicman.Entities.BusinessEntities.SearchResult> res = DataManager.Instance.SearchFolder(searchFileid, loaction);
            return res;
        }

    }
    
    public class FileDownloadHeader : SoapHeader
    {
        public bool exists;
    }
}
